 <template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px">
      <el-row>
        <el-col class="singleDatePicker">
          <el-form-item label="发放时间" size="small">
            <el-date-picker
              v-model="searchForm.issueDate"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              style="width: 190px">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-button type="primary" size="small" icon="el-icon-upload2" @click="downloadFile">导入</el-button>
      <input type="file" @change="fileChanged" ref="file"/>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :span-arr="spanArr"
      is-span-arr="welfaregive"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.welfareRegistrationId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="800px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
        <el-form-item prop="giveReason" label="福利发放事由" size="small">
          <el-autocomplete
            v-model="teamRow.giveReason"
            :fetch-suggestions="querySearchGiveReason"
            @select="handleSelectGiveReason"
            placeholder="请输入内容"
          >
          </el-autocomplete>
        </el-form-item>
        <el-form-item prop="issueDate" label="发放时间" size="small">
          <el-date-picker
            v-model="teamRow.issueDate"
            type="date"
            value-format="timestamp"
            placeholder="选择日期"
            style="width: 190px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="团队/部门" size="small">
          <!--<el-autocomplete-->
            <!--v-model="teamRow.teamName"-->
            <!--:fetch-suggestions="querySearchTeam"-->
            <!--@select="handleSelectTeam"-->
            <!--placeholder="请输入内容"-->
          <!--&gt;-->
          <!--</el-autocomplete>-->
          <el-input type="text" v-model="teamRow.teamName" disabled></el-input>
        </el-form-item>
        <el-form-item prop="receiptor" label="领取人" size="small">
          <el-input type="text" v-model="teamRow.receiptor"></el-input>
        </el-form-item>
        <el-form-item label="福利项目" :hidden="JSON.stringify(welfareItemList)==='[]'" size="small">
          <!--<el-button type="primary" icon="el-icon-plus" @click="addWelfareItemList()"></el-button>-->
        </el-form-item>
        <el-row v-for="(item,index) in welfareItemList">
          <el-col class="other">
            <el-form-item label="内容" size="small">
              <el-input type="text" v-model="item.content" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col class="other">
            <el-form-item label="数量" size="small">
              <el-input type="number" @input="amountChange" v-model.number="item.amount"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="other">
            <el-form-item label="单价" size="small">
              {{item.unitPrice}}
            </el-form-item>
          </el-col>
          <!--<el-col class="searchBtn">-->
          <!--<el-form-item size="small">-->
          <!--<el-button type="danger" size="small" icon="el-icon-minus" @click="delWelfareItemList(index)"></el-button>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-form-item label="总价" size="small">
          {{teamRow.totalSum}}
        </el-form-item>
        <el-form-item label="备注说明" size="small">
          <el-input type="textarea" v-model="teamRow.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    selectWelfareRegistration,
    addWelfareRegistration,
    getList,
    getGiveReason,
    deleteWelfareRegistration,
    updateWelfareRegistration,
    selectTeam,
    batchInsertwelfareRegistration
  } from '@/api/welfaregivechild'
  import myTable from '@/components/myTable'

  import { Message } from 'element-ui'
  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const issueDate = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'giveReason', label: '福利发放事由', minWidth: '30%', fixed: true },
          { prop: 'issueDate', label: '发放时间', width: '150', component: issueDate },
          { prop: 'teamName', label: '团队/部门', minWidth: '20%' },
          { prop: 'receiptor', label: '领取人', minWidth: '15%' },
          { prop: 'content', label: '福利项目', minWidth: '10%' },
          { prop: 'amount', label: '领取数量', minWidth: '10%' },
          { prop: 'unitPrice', label: '单价', minWidth: '10%' },
          { prop: 'totalSum', label: '总价', minWidth: '10%' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '新增福利登记',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {
          giveReason: [
            { required: true, message: '请输入福利发放事由', trigger: 'change' }
          ],
          issueDate: [
            { required: true, message: '请选择发放时间', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入团队/部门', trigger: 'change' }
          ],
          receiptor: [
            { required: true, message: '请输入领取人', trigger: 'change' }
          ]
        },
        visible: false,
        welfareItemList: [],
        spanArr: []
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
      this.keyupSubmit()
    },
    computed: {
      teamId() {
        return this.$store.state.user.teamId
      },
      teamName() {
        return this.$store.state.user.teamName
      }
    },
    methods: {
      keyupSubmit() {
        document.onkeydown = e => {
          const _key = window.event.keyCode
          if (_key === 13) {
            this.search()
          }
        }
      },
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.getSpanArr(this.tableData)
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增福利登记'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.teamRow.isTender = 1
        this.welfareItemList = []
        this.dialogType = 1
        this.$set(this.teamRow, 'teamId', this.teamId)
        this.$set(this.teamRow, 'teamName', this.teamName)
      },
      editTeam(welfareRegistrationId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改福利登记'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.welfareItemList = []
        const params = {
          welfareRegistrationId: welfareRegistrationId
        }
        selectWelfareRegistration(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
          this.teamRow.totalSumBefore = this.teamRow.totalSum
          this.teamRow.welfareItemChildList.forEach(value => {
            this.welfareItemList.push({
              content: value.content,
              amount: value.amount,
              unitPrice: value.unitPrice,
              welfareItemId: value.welfareItemId
            })
          })
        })
      },
      submitForm(formName) {
        const params = {
          welfareId: this.teamRow.welfareId,
          issueDate: this.teamRow.issueDate,
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          receiptor: this.teamRow.receiptor,
          welfareItemChildList: this.welfareItemList,
          totalSum: this.teamRow.totalSum,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        if (!this.dialogType) {
          params.welfareRegistrationId = this.teamRow.welfareRegistrationId
          params.totalSumBefore = this.teamRow.totalSumBefore
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              addWelfareRegistration(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateWelfareRegistration(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          welfareRegistrationId: scope.row.welfareRegistrationId,
          teamId: scope.row.teamId,
          totalSum: scope.row.totalSum,
          isDel: 1
        }
        deleteWelfareRegistration(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addWelfareItemList() {
        this.welfareItemList.push({
          content: '',
          amount: 0
        })
      },
      delWelfareItemList(index) {
        this.welfareItemList.splice(index, 1)
      },
      querySearchGiveReason(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            giveReason: queryString
          }
          getGiveReason(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.giveReason
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectGiveReason(item) {
        this.$set(this.teamRow, 'welfareId', item.welfareId)
        this.welfareItemList = item.welfareItemList
        this.welfareItemList.forEach(value => {
          delete value.welfareId
        })
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      getSpanArr(data) {
        this.spanArr = [] // 定义在vue的data中
        if (data == null) {
          return
        }
        for (var i = 0; i < data.length; i++) {
          if (i === 0) {
            this.spanArr.push(1)
            this.pos = 0
          } else {
            if (data[i].welfareRegistrationId === data[i - 1].welfareRegistrationId) {
              this.spanArr[this.pos] += 1
              this.spanArr.push(0)
            } else {
              this.spanArr.push(1)
              this.pos = i
            }
          }
        }
      },
      amountChange() {
        let totalSum = 0
        this.welfareItemList.forEach(value => {
          totalSum += value.amount * value.unitPrice
        })
        this.$set(this.teamRow, 'totalSum', totalSum)
      },
      downloadFile() {
        this.$refs.file.click()
      },
      fileChanged() {
        const excel = this.$refs.file.value
        const params = new FormData()
        console.log(this.$refs.file.value)
        var reg = /^.*\.(?:xls|xlsx)$/i
        if (!reg.test(excel)) {
          Message({
            message: '请上传excel格式的文件!',
            type: 'error',
            duration: 5 * 1000
          })
          return
        } else {
          params.append('file', this.$refs.file.files[0])
          batchInsertwelfareRegistration(params).then(response => {
            this.fetchData()
          })
          if (this.$refs.file) {
            this.$refs.file.value = ''
          }
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
    input[type="file"] {
      display: none;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
